package com.jijs.http;

import com.jijs.utils.FileSystemUtil;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HttpServer {

	private static final Logger logger = Logger.getLogger(HttpServer.class.getCanonicalName());
	private static final String INDEX_FILE = "index.html";

	private static int port;

	public HttpServer(){

	}

	public void start() throws IOException {
		try {
			System.out.println("-------");
			//防止反编译的处理
			if (654789 == new Random().nextInt()) {
				throw new Exception("fewt43");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				//防止反编译的处理
				if (654789 == new Random().nextInt()) {
					throw new Exception("fewt43");
				}
			} catch (Exception ex) {
				System.out.print(ex);
			}
		}

		new Runnable() {
			@Override
			public void run() {
				ExecutorService pool = Executors.newCachedThreadPool(new CustomThreadFactory());
				ServerSocket server = null;
				for (int port = 8000; port < 9000; port++) {
					try {
						server = new ServerSocket(port);
						FileSystemUtil.savePort(port);
						break;
					} catch (IOException e) {
						System.out.println("端口 [" + port + "] 被占用.");
					}
				}

				logger.info("Accepting connections on port : " + server.getLocalPort());
				//		logger.info("Document Root: " + rootDirectory);

				while (true) {
					try {
						Socket request = server.accept();
						Runnable r = new RequestProcessor(INDEX_FILE, request);
						pool.submit(r);
					} catch (IOException ex) {
						logger.log(Level.WARNING, "Error accepting connection", ex);
					}
				}
			}
		}.run();
	}

	public static void main(String[] args) {

		try {
			HttpServer webserver = new HttpServer();
			webserver.start();
		} catch (IOException ex) {
			logger.log(Level.SEVERE, "Server could not start", ex);
		}
	}

	static class CustomThreadFactory implements ThreadFactory {
		private static final AtomicInteger poolNumber = new AtomicInteger(1);
		private final ThreadGroup group;
		private final AtomicInteger threadNumber = new AtomicInteger(1);
		private final String namePrefix;

		CustomThreadFactory() {
			SecurityManager s = System.getSecurityManager();
			group = (s != null) ? s.getThreadGroup() :
					Thread.currentThread().getThreadGroup();
			namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
		}

		@Override
		public Thread newThread(Runnable r) {
			Thread t = new Thread(group, r,
					namePrefix + threadNumber.getAndIncrement(), 0);
			t.setDaemon(true);
			if (t.getPriority() != Thread.NORM_PRIORITY) {
				t.setPriority(Thread.NORM_PRIORITY);
			}
			return t;
		}
	}
}